package com.bbcare.nutritious.plat.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.HuamitechApiUtil;
import com.bbcare.comm.ResultModel;
import com.bbcare.nutritious.plat.service.IActivityHuamiService;

/**
 *
 * @name:         BloodSugarController.java
 * @author:       tao
 * @createTime:   2017年11月6日
 * @description:  手环运动控制器    --无会话接口
 * @modify:
 *
 */
@Controller
@RequestMapping("/webapi")
public class HuamiAuthorizationController {

    public static final Logger logger = Logger.getLogger(ActivityHuamiController.class);

    @Autowired
    private IActivityHuamiService activityHuamiService;

    //华米授权
    @ResponseBody
    @RequestMapping("/service/bindHuamiAccessToken")
    public ResultModel<Object> bindHuamiAccessToken(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in bindHuamiAccessToken----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out bindHuamiAccessToken----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"用户ID不能为空");
        }

        String code = requestParam.getString("code");
        if(StringUtils.isEmpty(code)){
        	logger.debug("out bindHuamiAccessToken----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"code不能为空");
        }

        /*String tenantId = requestParam.getString("tenantId");
        if(StringUtils.isEmpty(tenantId)){
        	logger.debug("out bindHuamiAccessToken----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"租户id不能为空");
        }*/

        Map<String,Object> rspMap = activityHuamiService.bindHuamiAccessToken(requestParam);

        logger.debug("out bindHuamiAccessToken----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }

    //华米授权
    @RequestMapping("/redirect/{userId}")
    public ModelAndView toRedirect(HttpServletRequest request,@PathVariable(value="userId") String userId)
            throws Exception {
        logger.info("in toRedirect----arg==" +userId);
//        String toList = "https://user.huami.com/oauth/index.html#/?client_id=3799138045645496&redirect_uri=http://doctor.bb-care.com/oms&response_type=code&token=access&token=refresh&state=11111#2222#3333";
        Map<String,Object> urlMap= new HashMap<String,Object>();
    	urlMap.put("userId",userId);
		String toUrl = HuamitechApiUtil.buildHuamiUrl(urlMap);
        return  new ModelAndView(new RedirectView(toUrl));
    }


}
